<template>
  <div class="bloc-column--word">
    <ColumnWordCloud
      v-if="columns.length > 0"
      :optionsData="data"
      :optionsColors="myColors"
      :optionsLimit="limitSize"
      @word-click-handler="wordClickHandler"
    />
  </div>
</template>
<!-- 
  设计column的内容, 业务逻辑
  1. 在create阶段 获取columns的数据
  2. 根据 vue-wordcloud 词云组件绑定数据 词云组件直接是返回一个组件
  3. 点击词语属性获取对应的columnid

  设计添加column按钮
  行为
  1. 点击column, 出现modal, 
  2. 输入column内容, 提交请求
  3. 刷新column路由的数据

  1. 如果点击分类后, 没有文章, 就在articles中更换一个页面
  出现, 去写一篇文章吧
  2. 点击去写文章, 跳转editor
  3. 跳转时将columnId带上, editor进行承接, 自动渲染中分类标题
  4. 改造article路由的数据, 通过路由传递过来

-->
<script setup lang="ts">
import { ElNotification } from 'element-plus'
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'

import $http from '@/api/http'
import ColumnWordCloud from '@/components/ColumnWordCloud.vue'
import { $bus } from '@/unit/mitt'

let router = useRouter()
let columns = ref<any>([])
let myColors = ref<string[]>(['#1f77b4', '#629fc9', '#94bedb', '#c9e0ef'])
let columnId = ref<string>()
let innerWidth = ref<number>()
let data = computed(() => {
  return {
    series: [
      {
        gridSize: 50,
        data: columns.value?.map((item) => {
          return {
            name: item.name,
            value: item.aids?.length || 1,
          }
        }),
      },
    ],
  }
})
// 相当于innerWidth = window的视口大小(响应式), 如果宽度发生改变, 跟随chart重新渲染, 最终达到适合屏幕大小的效果
let limitSize = computed(() => {
  let windowSize = (innerWidth.value || 0) / 300 // 1800 / 100 = 18
  let minSize = Math.max(windowSize * 5, 20)
  let maxSize = Math.max(Math.min(windowSize * 20, 200), 20)
  return [minSize, maxSize]
})

onMounted(() => {
  resizeHandle()
  getColumns()
  // TODO, 统一完成eventBus
  $bus.on('handleResetData', () => {
    getColumns()
  })
})
onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeHandle)
})
window.addEventListener('resize', resizeHandle)
async function getColumns() {
  try {
    let result = await $http({ type: 'columns' })
    columns.value = result.data.list
  } catch (err) {
    console.log(err)
    ElNotification({
      title: '错误',
      message: '文章分类为被获取到',
      type: 'error',
    })
  }
}

function wordClickHandler(name) {
  columnId.value = columns.value.find((item) => item.name === name).id
  // 获取到了columnId, 根据query形式传递到articles路由, 根据columnId, 获取对应文章
  router.push({ name: 'index', query: { columns: columnId.value } })
}
function resizeHandle() {
  innerWidth.value = window.innerWidth
}
</script>
<style scoped lang="less">
.bestsellers-container {
  height: 18.56rem;
  background: #f0f0f0;
}
</style>
